package com.xbn.xbnmall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbn.common.exception.PasswordErrorException;
import com.xbn.common.exception.PhoneExistException;
import com.xbn.common.exception.UserNotFindException;
import com.xbn.common.exception.UsernameExistException;
import com.xbn.common.to.MemberRegistTo;
import com.xbn.common.utils.HttpUtils;
import com.xbn.xbnmall.member.dao.MemberLevelDao;
import com.xbn.xbnmall.member.entity.MemberLevelEntity;
import com.xbn.xbnmall.member.vo.UserLoginVo;
import com.xbn.xbnmall.member.vo.WeiboUserToken;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xbn.common.utils.PageUtils;
import com.xbn.common.utils.Query;

import com.xbn.xbnmall.member.dao.MemberDao;
import com.xbn.xbnmall.member.entity.MemberEntity;
import com.xbn.xbnmall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistTo memberRegistTo) {
        MemberEntity memberEntity=new MemberEntity();

        //设置默认会员等级
        MemberLevelEntity memberLevelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(memberLevelEntity.getId());
        //设置启用状态
        memberEntity.setStatus(1);
        //设置昵称
        memberEntity.setNickname(memberEntity.getUsername());
        //设置注册时间
        memberEntity.setCreateTime(new Date());
        //设置手机、用户名，检查这两个的唯一性
        checkPhoneUnique(memberRegistTo.getPhone());
        checkUsernameUnique(memberRegistTo.getUserName());
        memberEntity.setMobile(memberRegistTo.getPhone());
        memberEntity.setUsername(memberRegistTo.getUserName());
        //密码加密
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        String encodePass=bCryptPasswordEncoder.encode(memberRegistTo.getPassword());
        memberEntity.setPassword(encodePass);

        this.baseMapper.insert(memberEntity);
    }

    @Override
    public void checkUsernameUnique(String username) {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>()
                .eq("username", username));
        if(count>0)
        {
            throw new UsernameExistException();
        }
    }

    @Override
    public void checkPhoneUnique(String phone) {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>()
                .eq("mobile", phone));
        if(count>0)
        {
            throw new PhoneExistException();
        }
    }

    @Override
    public MemberEntity login(UserLoginVo userLoginVo) {
        MemberEntity memberEntity=this.baseMapper.selectOne(
                new QueryWrapper<MemberEntity>()
                .eq("username",userLoginVo.getLoginacct())
                .or()
                .eq("mobile",userLoginVo.getLoginacct())
        );
        if(memberEntity==null)
        {
            throw new UserNotFindException();
        }
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        boolean matches = bCryptPasswordEncoder.matches(userLoginVo.getPassword(), memberEntity.getPassword());
        if(matches)
        {
            return memberEntity;
            //密码匹配成功
        }
        else {
            throw new PasswordErrorException();
        }


    }

    @Override
    public MemberEntity login(WeiboUserToken weiboUserToken) throws Exception {
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>()
                .eq("weibo_uid", weiboUserToken.getUid()));
        if(memberEntity!=null)
        {
            //该微博用户注册过了，只需要更新令牌相关东西就好了
            MemberEntity update=new MemberEntity();
            update.setId(memberEntity.getId());
            update.setWeiboExpiresIn(weiboUserToken.getExpires_in());
            update.setWeiboUid(weiboUserToken.getUid());
            this.baseMapper.updateById(update);
            memberEntity.setWeiboExpiresIn(weiboUserToken.getExpires_in());
            memberEntity.setWeiboToken(weiboUserToken.getAccess_token());
            return memberEntity;
        }
        else {
            //没有登陆过就注册，先去查询该用户的微博信息
            MemberEntity regist=new MemberEntity();
            try {
                HashMap<String ,String> map=new HashMap<>();
                map.put("access_token",weiboUserToken.getAccess_token());
                map.put("uid",weiboUserToken.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json",
                        "get", null, map);
                if(response.getStatusLine().getStatusCode()==200)
                {
                    //查询成功
                    String json= EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject=JSON.parseObject(json);
                    //获取微博昵称
                    String nickname = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    regist.setNickname(nickname);
                    regist.setGender("m".equals(gender)?1:0);
                }
            }catch (Exception e)
            {
log.error(e.getMessage());
            }

            regist.setLevelId(memberLevelDao.getDefaultLevel().getId());
            regist.setWeiboUid(weiboUserToken.getUid());
            regist.setWeiboToken(weiboUserToken.getAccess_token());
            regist.setWeiboExpiresIn(weiboUserToken.getExpires_in());
            this.baseMapper.insert(regist);
            return regist;
        }

    }

}